<!-- 录入凭证页面 -->
<template xmlns:>
  <div class="padding">
    <el-card>
      <div class="text-right margin-bottom">
        <el-button-group>
          <el-button
            type="danger"
            size="mini"
            @click="deleteFinanceVoucherById"
          >
            删除
          </el-button>
          <el-button
            type="warning"
            size="mini"
            @click="updateForceLock"
          >
            锁定
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="openCopyFinanceVoucherById"
          >
            复制
          </el-button>
          <el-button
            type="success"
            size="mini"
            @click="exportFinanceVoucherById"
          >
            导出
          </el-button>
        </el-button-group>
      </div>

      <div class="my_border">
        <div class="my_titile">查看记账凭证</div>
        <div class="flex justify-end">
          <div class="margin-right margin-bottom">
            <span class="margin-right-sm">日期：</span>
            {{ accountDate }}
          </div>
          <div>
            <span class="margin-right">凭证号：</span>
            <span>{{ voucherNo }}</span>
          </div>
        </div>
        <el-table
          border
          size="mini"
          class="text-sm"
          :data="tableData"
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column label="摘要" min-width="18%">
            <template slot-scope="scope">
              <div class="inputDeep">
                {{ scope.row.digest }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="会计科目"
            prop="financeSubjectTd"
            min-width="30%"
            class-name="account-td"
          >
            <template slot-scope="scope">
              <el-row class="flex align-center">
                <el-col :span="12">
                  <div class="inputDeep">
                    {{ scope.row.financeSubjectTd }}
                  </div>
                </el-col>
                <el-col :span="12" class="border-left">
                  <el-row>
                    <el-col :span="12">
                      <div class="inputDeep">
                        {{ scope.row.current }}
                      </div>
                    </el-col>
                    <el-col :span="12" class="inputDeep border-left">
                      {{ scope.row.rate }}
                    </el-col>
                  </el-row>
                  <div class="inputDeep border-top">
                    {{ scope.row.currentRateMoney }}
                  </div>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="往来单位" min-width="18%">
            <template slot-scope="scope">
              <div class="text-box pointer">
                <template v-if="scope.row.withTheUnitType && scope.row.withTheUnitId">
                  <template v-if="scope.row.withTheUnitType == 1">
                    {{userSourceMap[scope.row.withTheUnitId]}}
                  </template>
                  <template v-else-if="scope.row.withTheUnitType == 2">
                    {{customerMap[scope.row.withTheUnitId]}}
                  </template>
                  <template v-else-if="scope.row.withTheUnitType == 3">
                    {{serveCompanyMap[scope.row.withTheUnitId]}}
                  </template>
                </template>
                <template v-else>
                  <span v-for="item in scope.row.departId" :key="item">
                  <template v-if="initData.organizationDepartmentSource">
                    {{ initData.organizationDepartmentSource[item] }}
                  </template>
                  <template v-else>
                    item
                  </template>
                </span>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="借方金额" prop="debitMoney" min-width="16%">
            <template slot-scope="scope">
              <div class="inputDeep">
                {{ scope.row.debitMoney }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="贷方金额" prop="creditorMoney" min-width="16%">
            <template slot-scope="scope">
              <div class="inputDeep">
                {{ scope.row.creditorMoney }}
              </div>
            </template>
          </el-table-column>
        </el-table>


        <div class="margin-top" style="text-align: end">
          <span
            >制单:&nbsp;&nbsp;{{
              cuser ? userSourceMap[cuser] : $store.state.auth.user.name
            }}</span
          >
        </div>
      </div>
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <template v-if="selectedInput === 0">
        <el-tabs v-model="categoryActiveName" type="card">
          <el-tab-pane
            v-for="(item, value) in initData.financeCategoryVOS"
            :key="value"
            :label="value"
            :name="value"
          >
            <div class="padding">
              <el-radio-group v-model="radio" @change="changeRadio">
                <el-radio v-for="r in item" :key="r" :label="r"></el-radio>
              </el-radio-group>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else-if="selectedInput === 1">
        <el-tabs v-model="subjectTypeName" type="card">
          <el-tab-pane
            v-for="(item, value) in initData.subjectTypeDataMapJson"
            :key="value"
            :label="m(initData.financeSubjectTypeSourceMap[value])"
            :name="value"
          >
            <el-tree
              :data="item"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
            </el-tree>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else-if="selectedInput === 2">
        <el-table
          size="mini"
          :data="initData.configCurType"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column prop="currency" label="币种"></el-table-column>
          <el-table-column prop="exchangeRate" label="汇率"></el-table-column>
          <el-table-column prop="useDate" label="使用期间"></el-table-column>
        </el-table>
      </template>
      <template v-else-if="selectedInput === 3">
        <el-row :gutter="10" class="flex align-center">
          <el-col :span="2">部门：</el-col>
          <el-col :span="20">
            <el-select
              v-model="departId"
              multiple
              placeholder="请选择"
              size="mini"
            >
              <el-option
                v-for="(item, val) in initData.organizationDepartmentSource"
                :key="val"
                :label="item"
                :value="val"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2">
            <el-link @click="selectAll">全选</el-link>
          </el-col>
        </el-row>
      </template>
      <span slot="footer" class="dialog-footer" v-if="selectedInput === 3">
        <el-button size="mini" @click="cancelSelect">取 消</el-button>
        <el-button size="mini" type="primary" @click="enterSelect">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import globalData from "@/utils/config";
//全局文件 配置
import * as constant from "@/store/yg/common/constant";

export default {
  data() {
    return {
      initData: {},
      fileUrl: constant.FILE_SERVER,
      // fileUrl: constant.FILE_SERVER,
      cuser: "",
      dialogTitle: "",
      categoryActiveName: "first",
      subjectTypeName: "first",
      dialogVisible: false,
      selectedTdIndex: 0,
      selectedInput: 0,
      accountDate:
        new Date().getUTCFullYear() +
        "-" +
        (parseInt(new Date().getMonth()) + parseInt(1)) +
        "-" +
        parseInt(new Date().getDate()),
      accountMonth:
        new Date().getUTCFullYear() +
        "-" +
        ("0" + (new Date().getMonth() + 1)).slice(-2),
      voucherNo: 1,
      sign: "",
      radio: "",
      departId: [],
      search: {
        abstract: "",
        subjects: "",
        share: "",
        debit: "",
        credit: ""
      },
      tableData: [
        {
          digest: "", // 摘要
          financeSubjectTd: "", //会计科目
          current: "", //币种
          rate: "", // 汇率
          currentRateMoney: "",
          departId: "", // 分摊部门
          withTheUnitType: "",//往来单位类型
          withTheUnitId: "",//往来单位ID
          debitMoney: "", // 借方金额
          creditorMoney: "" //贷方金额
        }
      ],
      defaultProps: {
        children: "financeSubjectNodes",
        label: "label"
      },
      userSourceMap: {},
      customerMap: {},
      serveCompanyMap: {},
      dealingsObjectMap: {},
      financeSubjectWithTheUnitTypes:[],
      financeAccountNo: "",
      // totalMoney:"",
    };
  },
  computed: {
    tableTotal() {
      let totalDebitMoney = 0; //借方金额总计
      let totalCreditorMoney = 0; // 贷方金额总计
      for (const i of this.tableData) {
        if (!isNaN(parseFloat(i.debitMoney))) {
          totalDebitMoney += parseFloat(i.debitMoney);
        }
        if (!isNaN(parseFloat(i.creditorMoney))) {
          totalCreditorMoney += parseFloat(i.creditorMoney);
        }
      }
      totalDebitMoney = totalDebitMoney.toFixed(2);
      totalCreditorMoney = totalCreditorMoney.toFixed(2);
      // this.totalMoney = totalDebitMoney;
      console.log('totalDebitMoney :>> ', totalDebitMoney);
      return {
        totalDebitMoney,
        totalCreditorMoney
      };
    }
  },
  mounted() {
    console.log("ttt", this.$route);
    console.log("this.data :>> ", this.$store.state.auth);
    this.init();
    this.financeAccountNo = this.$route.query.financeAccountNo;
  },
  methods: {
    m(k) {
      return m(k);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计:"
          sums[1] = this.digitUppercase(this.tableTotal.totalDebitMoney);
          return;
        }
        console.log('column :>> ', column);
        switch (
          column.property // column.property可以匹配它的每一列的命名， 然后赋值
        ) {
          case "debitMoney":
            sums[index] = this.tableTotal.totalDebitMoney; //值取自后台
            break;
          case "creditorMoney":
            sums[index] = this.tableTotal.totalCreditorMoney; //值取自后台
            break;

          default:
            break;
        }
      });

      return sums;
    },
    digitUppercase(n) {
      if(!n) return
      var fraction = ['角', '分'];
      var digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
      ];
      var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ];
      var head = n < 0 ? '欠' : '';
      n = Math.abs(n);
      var s = '';
      for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
      }
      s = s || '整';
      n = Math.floor(n);
      for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
      }
      return head + s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
    },
    async init() {
      const { code, data, message } = await ajax("saveEditInit", {});
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      }
      const configCurType = [];
      for (const i in data.configCurType) {
        configCurType.push({
          currency: i,
          exchangeRate: data.configCurType[i],
          useDate: new Date().toLocaleDateString().slice(0, 6)
        });
      }
      const parentAndSubMap = [];
      for (const i in data.parentAndSubMap) {
        let obj = {
          name: i,
          label: i
        };
        for (const j of data.parentAndSubMap[i]) {
        }
        parentAndSubMap.push(obj);
      }
      const categoryList = [];
      const subjectTypeList = [];
      for (const i in data.financeCategoryVOS) {
        categoryList.push(i);
      }
      for (const i in data.subjectTypeDataMapJson) {
        subjectTypeList.push(i);
        this.sortData(data.subjectTypeDataMapJson[i]);
      }
      console.log(
        "data.subjectTypeDataMapJson :>> ",
        data.subjectTypeDataMapJson
      );
      console.log("configCurType :>> ", configCurType);
      this.userSourceMap = data.userSourceMap;
      this.customerMap = data.customerMap;
      this.serveCompanyMap = data.serveCompanyMap;
      this.dealingsObjectMap = data.dealingsObjectMap;
      this.initData.configCurType = configCurType;
      this.initData.parentAndSubMap = parentAndSubMap;
      this.initData.organizationDepartmentSource =
        data.organizationDepartmentSource;
      this.initData.subjectTypeDataMapJson = data.subjectTypeDataMapJson;
      this.initData.financeCategoryVOS = data.financeCategoryVOS;
      this.initData.financeSubjectTypeSourceMap =
        data.financeSubjectTypeSourceMap;
      this.categoryActiveName = categoryList[0];
      this.subjectTypeName = subjectTypeList[0];
      this.voucherNo = data.voucherNo;
      if (this.$route.query.pid) {
        this.getInfo(this.$route.query.pid);
      }
    },

    sortData(data) {
      for (const j of data) {
        j.label = j.financeSubject.no + " " + j.financeSubject.name;
        if (
          Object.prototype.toString.call(j.financeSubjectNodes) ===
          "[object Array]"
        ) {
          this.sortData(j.financeSubjectNodes);
        }
      }
      return data;
    },
    selectedTd(scope, index) {
      console.log("scope :>> ", scope);
      this.selectedTdIndex = scope.$index;
      this.selectedInput = index;
      this.dialogVisible = true;
      switch (index) {
        case 0:
          this.dialogTitle = "请选择摘要";
          break;
        case 1:
          this.dialogTitle = "请选择科目";
          break;
        case 2:
          this.dialogTitle = "请选择币种汇率";
          break;
        case 3:
          this.dialogTitle = "请选择往来单位";
          break;
      }
    },
    handleNodeClick(d, n, l) {
      if (d.financeSubjectNodes) {
        return;
      }
      this.dialogVisible = false;
      this.tableData[this.selectedTdIndex].financeSubjectTd = d.label;
    },
    selectAll() {
      let arr = [];
      for (const i in this.initData.organizationDepartmentSource) {
        arr.push(i);
      }
      this.departId = arr;
    },
    enterSelect() {
      this.dialogVisible = false;
      this.tableData[this.selectedTdIndex].departId = this.departId;
    },
    cancelSelect() {
      this.dialogVisible = false;
      this.departId = [];
    },
    handleCurrentChange(val) {
      console.log("val :>> ", val);
      this.dialogVisible = false;
      this.tableData[this.selectedTdIndex].current = val.currency;
      this.tableData[this.selectedTdIndex].rate = val.exchangeRate;
    },
    changeRadio() {
      this.dialogVisible = false;
      this.tableData[this.selectedTdIndex].digest = this.radio;
    },
    async getInfo(id) {
      const params = {};
      params["id"] = id;
      console.log(params);
      const { code, data, data2, message } = await ajax(
        "viewFinanceVoucher",
        params
      );
      if (code === 200) {
        //赋值上面的时间
        this.accountDate = data.accountDate;
        this.voucherNo = data.voucherNo;
        this.cuser = data.cuser;
        // financeSubjectTd
        // departId
        if (data.financeVoucherDetails) {
          for (const i of data.financeVoucherDetails) {
            i.departId = i.departList;
            i.financeSubjectTd =
              i.financeSubjectNo + " " + (data2[i.financeSubjectNo] || "");
          }
          //借方金额科目放在上面
          // data.financeVoucherDetails.map((currentValue, index, arr) => {
          //   if (currentValue["debitMoney"]) {
          //     arr.splice(index, 1);
          //     arr.splice(0, 0, currentValue);
          //   }
          // })
          this.tableData = data.financeVoucherDetails;
        } else {
          this.$message.error("凭证详情初始化失败");
        }
      } else {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      }
    },
    //删除凭证
    async deleteFinanceVoucherById() {
      const { code, data, message } = await ajax(
        "deleteFinanceVoucherByIdView",
        { id: this.$route.query.pid }
      );
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      } else if (code === 200) {
        this.$message.success("删除成功");
        window.open("/#/main/finance__voucher__list", "_self");
      } else {
        this.$message.error("未知异常");
      }
    },
    updateForceLock(){
      ajax("updateForceLocked", {"id":this.$route.query.pid}).then(
        res => {
          const code = res.code;
          if (code === 200) {
            this.$message.success("操作成功");
          } else {
            this.$message.error(m(res.message));
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    //复制当前凭证
    openCopyFinanceVoucherById() {
      window.open(
        "/#/blank/finance__voucher__copy?pid=" + this.$route.query.pid
      );
    },
    //导出凭证
    async exportFinanceVoucherById() {
      const {
        code,
        data,
        data2,
        message
      } = await ajax("exportFinanceVoucherById", { id: this.$route.query.pid });
      if (code !== 200) {
        if (message) {
          this.$message.error(message);
        } else {
          this.$message.error("服务器异常");
        }
      } else if (code === 200) {
        this.$message.success("生成成功");

        //老方法
        // this.$message.success("生成成功");
        // window.location.href = this.fileUrl + data;

        var path = constant.FILE_SERVER + data;
        location.href =
          constant.API_SERVER +
          "/open/downloadFileByHttp?fileName=" +
          data2 +
          "&path=" +
          path +
          "/" +
          data2;
      } else {
        this.$message.error("未知异常");
      }
    }
  }
};
</script>

<style scoped>
.my_border {
  margin: 0 auto;
  border: 1px solid #ccc;
  padding: 20px;
}

.my_titile {
  text-align: center;
  height: 30px;
  line-height: 30px;
  font-size: 24px;
  margin-bottom: 20px;
}

.my_margin {
  margin-right: 388px;
  margin-bottom: 20px;
}

.inputDeep >>> .el-input__inner {
  border: 0;
}

/deep/ .el-table tbody tr:hover > td {
  background-color: #fff;
}

/deep/ .el-table--mini td,
.el-table--mini th {
  padding: 0;
}

/deep/ .btn-box .el-button {
  padding: 0;
}

/deep/ .el-dialog__body {
  padding-top: 10px;
}

/deep/ .cell,
.el-select {
  width: 100%;
}

/deep/ .account-td .cell {
  padding-right: 0;
}
</style>
<style lang="scss" scoped>
.border-left {
  border-left: 1px solid #ebeef5;
}

.border-top {
  border-top: 1px solid #ebeef5;
}

.text-box {
  width: 100%;
  min-height: 28px;
}

.table-box {
  background-color: ghostwhite;
}
</style>
